from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from apps.admin.utils import PageNum
from apps.goods.models import SKUImage
from apps.admin.serializers.images import SKUImageModelSerializer


class ImageModelViewSet(ModelViewSet):
    queryset = SKUImage.objects.all()
    serializer_class = SKUImageModelSerializer
    pagination_class = PageNum

    #重写create,图片保存
    def create(self, request, *args, **kwargs):
        image=request.data.get('image')
        image_data = image.read()
        sku_id = request.data.get('sku')
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        from fdfs_client.client import Fdfs_client
        client = Fdfs_client('utils/fastdfs/client.conf')
        result=client.upload_by_buffer(image_data)
        if result['Status'] !='Upload successed.':
            return Response(status=status.HTTP_400_BAD_REQUEST)
        file_id = result.get('Remote file_id')
        new_image=SKUImage.objects.create(
            sku_id=sku_id,
            image=file_id
        )
        return Response(
            {
                'id':new_image.id,
                'sku':sku_id,
                'image':new_image.image.url
            },
            status=status.HTTP_201_CREATED
        )




from apps.goods.models import SKU
from rest_framework.generics import GenericAPIView
from apps.admin.serializers.images import ImageSKUModelSerializer
from rest_framework.mixins import ListModelMixin
from rest_framework.generics import ListAPIView
class ImageSKUAPIView(ListAPIView):

    queryset = SKU.objects.all()
    serializer_class = ImageSKUModelSerializer

    # def get(self,request):
    #     return self.list(request)

        # skus = self.get_queryset()
        # serializer = self.get_serializer(skus,many = True)
        # return Response(serializer.data)

